package com.hangxintong.common.utils;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;

/**
 * @author Lenovo
 */
@Slf4j
@Data
@Component
public class CanvasImg {


    public static String PdfSavePath="";
    @Value("/www/hangxintong/upload/")
    public void setChineseFontPath(String chineseFontPathStr){
        PdfSavePath=chineseFontPathStr;
    }

    public static String returnUrl="";
    @Value("/www/hangxintong/upload/")
    public void setReturnUrl(String returnUrlStr){
        returnUrl = returnUrlStr;
    }
    public static void createImage(String fileLocation, BufferedImage image) {
        try {
            FileOutputStream fos = new FileOutputStream(fileLocation);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            ImageIO.write(image, "png", bos);
//            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
//            encoder.encode(image);
            bos.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void graphicsGeneration(String path, ArrayList<Map<String, String>> list) {
        int imageWidth = 500;// 图片的宽度
        int imageHeight = 500;// 图片的高度

        BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
        graphics.setColor(Color.white);
        graphics.fillRect(0, 0, imageWidth, imageHeight);
        graphics.setColor(Color.BLACK);

        int high = 30;
        int wigth = 0;
        graphics.setFont(new Font("宋体", Font.BOLD, 30));
        graphics.drawString("药方详情", 200, high);
        graphics.setFont(new Font("宋体", Font.BOLD, 20));
        high += 10;
        graphics.drawLine(0, high, 550, high);

        for (Map<String, String> rowMap : list) {
            high += 50;
            wigth = 40;
            for (Map.Entry<String, String> entry : rowMap.entrySet()) {
                String name = entry.getKey() + "：" + entry.getValue();
                if ("title".equals(entry.getKey())) {
                    high += 30;
                    graphics.setFont(new Font("黑体", Font.BOLD, 20));
                    graphics.drawString(entry.getValue(), wigth, high);
                    graphics.setFont(new Font("宋体", Font.BOLD, 20));
                } else {
                    graphics.drawString(name, wigth, high);
                    wigth += 160;
                }

            }
        }
        createImage(path, image);

    }
    /**
    * @Description
    * @Author  Bz.Mr
    * @Date   2020/12/10 9:14
    * 画图片  2竖版552*780|1横版 980*552
    * plate:1横版  2竖版
    */
    public static void graphicsGenerationJson(String path,String bg,List<Map<String,Object>> list,int plate) throws IOException {

        int imageWidth = 552;// 图片的宽度
        int imageHeight = 780;// 图片的高度
        if(plate==1){
            imageWidth = 980;
            imageHeight =552;
        }
        BufferedImage image = null;
        if(bg!=null&&!bg.equals("")){
            log.error("--------------->{}",webUrltoPathUrl(bg));
            image=resizeImage(imageWidth, imageHeight, ImageIO.read(new File(webUrltoPathUrl(bg))));
        }else{
            log.error("-----bg2{}",bg);
            image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
        }


        Graphics2D graphics = image.createGraphics();
        if(bg==null||bg.equals("")){
            graphics.setColor(Color.white);
            graphics.fillRect(0, 0, imageWidth, imageHeight);
        }
        graphics.setColor(Color.BLACK);

        for (Map<String,Object> rowMap : list) {
            if(rowMap.isEmpty()){ continue;}
            String imgSrc="";
            switch (rowMap.get("type").toString()){
                case "idPhoto":


                case "charutupian":
                    if(rowMap.get("imgSrc").toString().isEmpty()){ break;}
                    imgSrc = webUrltoPathUrl(rowMap.get("imgSrc").toString());
                    BufferedImage idPhoto = resizeImage(Integer.parseInt(rowMap.get("width").toString()), Integer.parseInt(rowMap.get("height").toString()), ImageIO.read(new File(imgSrc)));
                    graphics.drawImage(idPhoto, Integer.parseInt(rowMap.get("translateX").toString()), Integer.parseInt(rowMap.get("translateY").toString()), Integer.parseInt(rowMap.get("width").toString()), Integer.parseInt(rowMap.get("height").toString()), Color.LIGHT_GRAY,null);
                    break;
                default:
                    graphics.setFont(new Font("黑体", Font.BOLD, 20));
                    graphics.drawString(rowMap.get("val").toString(), Integer.parseInt(rowMap.get("translateX").toString()), Integer.parseInt(rowMap.get("translateY").toString()));

            }
        }
        createImage(path, image);

    }
    public String overlapImage(String backgroundPath, String qrCodePath, String wxHeadPath, String message, String outPutPath) {
        try {
            //设置图片大小
            BufferedImage background = resizeImage(750, 1208, ImageIO.read(new File(backgroundPath)));
//            BufferedImage qrCode = resizeImage(400, 400, ImageIO.read(new File(qrCodePath)));
//            BufferedImage qrHead = resizeImage(200, 200, ImageIO.read(new File(wxHeadPath)));
            //--------------------------------------------------
            Graphics2D g = background.createGraphics();
            g.setColor(Color.white);
            g.setFont(new Font("微软雅黑",Font.BOLD,20));
            g.drawString(message,530 ,220);
            //在背景图片上添加二维码图片
//            g.drawImage(qrHead, 276, 39, qrHead.getWidth(), qrHead.getHeight(), null);
//            g.drawImage(qrCode, 185, 550, qrCode.getWidth(), qrCode.getHeight(), null);
            g.dispose();
            ImageIO.write(background, "png", new File(outPutPath));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static BufferedImage resizeImage(int x, int y, BufferedImage bfi) {
        BufferedImage bufferedImage = new BufferedImage(x, y, BufferedImage.TYPE_INT_RGB);
        bufferedImage.getGraphics().drawImage(bfi.getScaledInstance(x, y, Image.SCALE_SMOOTH), 0, 0, null);
        return bufferedImage;
    }
    /**
     * 图片名生成
     **/
    public static String genImageName() {
        //取当前时间的长整形值包含毫秒
        long millis = System.currentTimeMillis();
        //加上三位随机数
        Random random = new Random();
        int end3 = random.nextInt(999);
        //如果不足三位前面补0
        String str = millis + String.format("%03d", end3);
        //创建文件夹
        String saveDir = new SimpleDateFormat("yyyyMMdd").format(new Date()).toString()+"/";
        File file = new File(PdfSavePath+"pdf/"+saveDir);
        if (!file.exists()) {
            file.mkdirs();
        }
        return PdfSavePath+"pdf/"+saveDir+str+".png";
    }
   /**
   * @Description
   * @Author  Bz.Mr
   * @Date   2020/12/10 13:22
   * type=1 模板信息
   * type=0 替换数据
   * 2竖版552*780|1横版 980*552
   * 0学员姓名 ，1学员性别 ，2部门、职位 3.证件号 ，4证件照 ， 5考试分数 ，6考试名称 ，7有效时期
   *
    * name 学员姓名    idPhoto 学员照片    sex 学员性别    position 部门、职位      certificate  证件号      kaoshifenshu 考试分数
    * kaoshimingcheng 考试名称   youxiaoshiqi   有效时期   zidingyiwenban    自定义文本   charutupian  插入图片
   */
    public static List<Map<String,Object>> composeData(String listJson,int type,String[] strArr ){
        List<Object> list = JSON.parseArray(listJson);
        List<Map<String, Object>> outList = new ArrayList<>();
        try{
            if(list.size()>0){
                for (Object ss :list){
                    Map<String, Object> strObject = (Map<String, Object>) ss;
                    if(type==0){
                        switch (strObject.get("type").toString()){
                            case "name" :
                                strObject.put("val",strArr[0]);
                                break;
                            case "sex":
                                strObject.put("val",strArr[1]);
                                break;
                            case "position":
                                strObject.put("val",strArr[2]);
                                break;
                            case "certificate":
                                strObject.put("val",strArr[3]);
                                break;
                            case "idPhoto":
                                strObject.put("val",strArr[4]);
                                break;
                            case "kaoshifenshu":
                                strObject.put("val",strArr[5]);
                                break;
                            case "kaoshimingcheng":
                                strObject.put("val",strArr[6]);
                                break;
                            case "youxiaoshiqi":
                                strObject.put("val",strArr[7]);
                                break;
                            default :
                                System.out.println("未知等级");
                        }
                    }

                    outList.add(strObject);
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return outList;
    }
    /**
     * @Description
     * @Author  Bz.Mr
     * @Date   2020/12/7 16:52
     * 内网地址转化成外网url图片地址
     */
    public static String returnsUrl(String pdfPath){
//        String pdfUrl = PdfSavePath + pdfPath.substring(returnUrl.length());
//        String picUrl = pdfUrl.substring(0,pdfUrl.indexOf("."))+pdfPath.substring(pdfPath.lastIndexOf("."));//pdfUrl.substring(pdfUrl.indexOf("."));
        return returnUrl+pdfPath.substring(PdfSavePath.length());
    }
    /**
     * @Description
     * @Author  Bz.Mr
     * @Date   2020/12/7 16:52
     * 外网url图片地址内网地址
     */
    public static String webUrltoPathUrl(String webPath){
        String pdfUrl = PdfSavePath + webPath.substring(returnUrl.length());
        return pdfUrl;
    }
    public static void main(String[] args) throws IOException {
        String bg="D:\\WWW\\hangxintong\\upload\\20201214\\a39db35e-c168-4c5b-8062-e34ff720e3b0.png";
        File file = new File(bg);
        System.out.println(file);
    }
    /**
    * @Description
    * @Author  Bz.Mr
    * @Date   2020/12/10 10:07
    *
    */
//    public static void main(String[] args) throws IOException {
////        ArrayList<Map<String, String>> list = new ArrayList<>();
////        for (int i = 0; i < 8; i++) {
////            Map<String, String> mapTitle = new HashMap<String, String>();
////            mapTitle.put("单价/克", "20.0");
////            mapTitle.put("克数", "1");
////            mapTitle.put("名称", "柴胡");
////            list.add(mapTitle);
////        }
//        String path = "E:/upload/image";
//        File newFileDir = new File(path);
//        //如果不存在 则创建
//        if (!newFileDir.exists()) {
//            newFileDir.mkdirs();
//        }
////        graphicsGeneration(path + "/" + genImageName() + ".jpg", list);
//        CanvasImg canvasImg = new CanvasImg();
////        System.out.println("1111111111"+canvasImg.getC);
//        String  s= "[{\"type\":\"name\",\"width\":150,\"height\":50,\"translateX\":95,\"translateY\":215,\"key\":\"1607585390000_7328\",\"val\":\"学员姓名\"},{\"type\":\"sex\",\"width\":150,\"height\":50,\"translateX\":95,\"translateY\":300,\"key\":\"1607585391000_36582\",\"val\":\"学员性别\"},{\"type\":\"certificate\",\"width\":150,\"height\":50,\"translateX\":355,\"translateY\":390,\"key\":\"1607585392000_85610\",\"val\":\"证件号\"},{\"type\":\"position\",\"width\":150,\"height\":50,\"translateX\":95,\"translateY\":390,\"key\":\"1607585392000_52028\",\"val\":\"部门、职位\"},{\"type\":\"idPhoto\",\"width\":150,\"height\":150,\"translateX\":349,\"translateY\":212,\"key\":\"1607585393000_63178\",\"imgSrc\":\"\",\"val\":\"学员照片\"},{\"type\":\"kaoshifenshu\",\"width\":150,\"height\":50,\"translateX\":225,\"translateY\":666,\"key\":\"1607585394000_70675\",\"val\":\"考试分数\"},{\"type\":\"kaoshimingcheng\",\"width\":150,\"height\":50,\"translateX\":95,\"translateY\":465,\"key\":\"1607585395000_77272\",\"val\":\"考试名称\"},{\"type\":\"youxiaoshiqi\",\"width\":150,\"height\":50,\"translateX\":355,\"translateY\":465,\"key\":\"1607585396000_49426\",\"val\":\"有效时期\"},{\"type\":\"zidingyiwenban\",\"width\":350,\"height\":80,\"translateX\":135,\"translateY\":575,\"key\":\"1607585396000_79556\",\"val\":\"自定义文本\"},{\"type\":\"charutupian\",\"width\":150,\"height\":150,\"translateX\":360,\"translateY\":620,\"key\":\"1607585397000_43783\",\"imgSrc\":\"C:/Users/Lenovo/Desktop/pdf/photo.jpg\",\"val\":\"插入图片\"},{\"type\":\"charutupian\",\"width\":150,\"height\":150,\"translateX\":316,\"translateY\":44,\"key\":\"1607587042000_6002\",\"imgSrc\":\"C:/Users/Lenovo/Desktop/pdf/photo.jpg\",\"val\":\"插入图片\"}]";
////        JSONObject jsonObject = JSONObject.parseObject(s);
////        Object parse = JSON.parse(s);
//        List<Object> list;
//        list = JSON.parseArray(s);
//        String[] array = new String[8];
//        array[0]="张荣钢";
//        array[1]="女";
//        array[2]="暂无";
//        array[3]="20121425365425002";
//        array[4]="C:\\Users\\Lenovo\\Desktop\\pdf\\photo.jpg";
//        array[5]="100";
//        array[6]="2020综合期末考试";
//        array[7]="2020-12-31";
//        List<Map<String, Object>> maps = composeData(s, 0, array);
//
//        String bg="C:\\Users\\Lenovo\\Desktop\\pdf\\bg.jpg";
//        String s1 = genImageName();
//        System.out.println(s1);
//        canvasImg.graphicsGenerationJson(genImageName(),bg,maps,2);
//
//       // canvasImg.overlapImage("C:\\Users\\Lenovo\\Desktop\\pdf\\bg.jpg", "", "", "哈发发", "E:\\upload\\image\\a.jpg");
////        List<Map<String, Object>> maps = composeData(s, 1, null);
//        for (Map<String,Object> ss :maps){
//            log.error("{}",ss);
//        }
//
//    }
}